import argopt
import re
import time
import os

def find_function(line):
    result = re.findall(r'([a-z0-9_]+)\(',line)
    if result:
        return (line.find(";") < 0) and (line.find("}") < 0)
    return False


'''
    add any key words which you don't want to stubbing.
'''


def isKeyWordWithLeftBrace(name):
    functions_do_not_stubing = [
        "interpol_s16_s16",
        "abs"
    ]
    keys = ["pal_memzero","if","elif","for", "switch", "case", "sizeof","return",
            "max2_u8","max2_s8","max2_u16","max2_s16","max2_u32","max2_s32","max2_f32","max3_u8","max3_s8","max3_u16","max3_s16","max3_u32","max3_s32","max3_f32","max4_u8","max4_s8","max4_u16",
            "max4_s16","max4_u32","max4_s32","max4_f32","middle_u8", "middle_s8", "middle_u16","middle_s16","middle_u32","middle_s32","middle_f32"]

    for key in keys:
        if key == name:
            return True
    for key in functions_do_not_stubing:
        if key == name:
            return True
    return False



def stub_the_called_function(line):
    result = re.findall(r'([a-zA-Z0-9_]+)\(',line)
    if result:
        for func_name in result:
            if isKeyWordWithLeftBrace(func_name):
                continue
            if func_name[0:5] != "STUB_":
                line = line.replace((func_name+"("),("STUB_"+func_name+"("))
    return line



if __name__ == "__main__":
    data = [
        {'name': 'c_file_path',  'type':     type(str),
         'default': "test_c_file\\random_map.c",     'comment': 'c file path'},
        # {'name': 'c_file_path',      'type':     type(int),
        #  'default': 30,     'comment': 'lines number'},
        {'name': 'help',      'type':     type(bool),
         'default': False,    'comment': 'generate the date map code. and insert it to  '}
    ]

    help_text = """
    stub_tool
      syntax:
                        stub_tool.py c_file_path=    
      example:
                        stub_tool.py c_file_path=C:/sandBox/timex/unittest/x86/workspace/src/random_map/random_map.c 
    """

    error, unknown, args, opts = argopt.parse(data, help_text)



    if opts['c_file_path'] == None:
        print('miss c file path,and will be closed in 3 seconds')
        time.sleep(3)
        exit(0)

    fp = open(opts['c_file_path'])
    if fp == None:
        print('c file path error ,and will be closed in 3 seconds')
        time.sleep(3)
        exit(0)

    lines = []
    for line in fp:
        lines.append(line)
    fp.close()

    bakpath = str(opts['c_file_path']).replace('/','\\')

    os.system("echo f| xcopy " + bakpath + " " + bakpath + ".bak")

    remove_flag = False

    is_in_function = False
    is_in_comment = False
    i = -1
    while i < len(lines) -1:
        i += 1
        if is_in_comment:
            if lines[i].find("*/") > 0:
                is_in_comment = False
            else:
                continue
        elif lines[i].find("/*") >= 0:
            if lines[i].find("*/") < 0:
                is_in_comment = True
                continue
        elif lines[i].strip()[0:2] == "//":
            continue

        if is_in_function:
            if lines[i][0] == '}':
                is_in_function = False
            else:
                lines[i] = stub_the_called_function(lines[i])
        elif find_function(lines[i]):
            is_in_function = True
    fp = open(opts['c_file_path'], 'w')
    for line in lines:
        fp.write(line)
    fp.close()
